package com.three.reward;

import com.three.exception.GameException;

import java.lang.reflect.Constructor;

/**
 * 奖励模块抽象类
 * Created by mathua on 2017/6/23.
 */
public abstract class RewardBase {
    protected final RewardType type;// 奖励类型
    protected final long param;// 奖励物品标志
    protected final long holderId;// 持有者id
    protected long amount;// 奖励数量
    // TODO 以后还要根据物品功能扩展参数

    public RewardBase(RewardItem item, long holderId) {
        this.type = item.getType();
        this.param = item.getParam();
        this.amount = item.getAmount();
        this.holderId = holderId;
    }

    /**
     * 增加奖励数量
     *
     * @param value 增加量
     * @return
     */
    public boolean addAmount(long value) {
        if (value < 0)
            return false;
        amount += value;
        return true;
    }

    /**
     * 是否可以领取
     */
    public abstract void canHandOut() throws GameException;

    /**
     * 发放奖励
     * @param overflowToMail 溢出用邮件发送
     * @return 返回存不下的量
     */
    public abstract RewardItem handOutReward(boolean overflowToMail);

    /**
     * 构造一个奖励
     *
     * @param item     奖励的数据
     * @param holderId 奖励的持有者
     * @return
     */
    public static RewardBase valueOf(RewardItem item, long holderId) {
        try {
            RewardType type = item.getType();
            Class<? extends RewardBase> classOfT = type.getClassOfT();
            Constructor constructor = classOfT.getConstructor(new Class[]{RewardItem.class, Long.class});
            constructor.setAccessible(true);
            return (RewardBase) constructor.newInstance(new Object[]{item, holderId});
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        RewardBase that = (RewardBase) o;

        if (param != that.param) return false;
        if (holderId != that.holderId) return false;
        return type == that.type;
    }
}
